﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace ImvuCacheViewer
{
    public class CVEntry {
        public string Filename { get; set; }
        public DateTime Date { get; set; }
        public Size Size { get; set; }
        public ImageType Type { get; set; }
        private byte[] SmallBits { get; set; }
        private byte[] LargeBits { get; set; }

        public override string ToString() {
            string result = string.Empty;
            result += Filename + "\t";
            result += Date + "\t";
            result += Size.Width + "\t";
            result += Size.Height + "\t";
            result += Type + "\t";
            result += Convert.ToBase64String(SmallBits) + "\t";
            result += Convert.ToBase64String(LargeBits);
            return result;
        }

        public CVEntry() {}
        public CVEntry(string line) {
            string[] pieces = line.Split('\t');
            Filename = pieces[0];
            Date = DateTime.Parse(pieces[1]);
            Size = new Size(int.Parse(pieces[2]), int.Parse(pieces[3]));
            Type = (ImageType) Enum.Parse(typeof (ImageType), pieces[4]);
            SmallBits = Convert.FromBase64String(pieces[5]);
            LargeBits = Convert.FromBase64String(pieces[6]);
        }

        private void SetBits(string which, Image b) {
            using (MemoryStream ms = new MemoryStream()) {
                switch (Type) {
                    case ImageType.Gif:
                        b.Save(ms, ImageFormat.Gif);
                        break;
                    case ImageType.Jpg:
                        b.Save(ms, ImageFormat.Jpeg);
                        break;
                    case ImageType.Png:
                        b.Save(ms, ImageFormat.Png);
                        break;
                    default:
                        return;
                }
                if (which == "Small") {
                    SmallBits = ms.ToArray();
                } else {
                    LargeBits = ms.ToArray();
                }
            }
        }

        public Bitmap SmallImage {
            get { return Image.FromStream(new MemoryStream(SmallBits)) as Bitmap; }
            set { SetBits("Small", value); }
        }

        public Bitmap LargeImage {
            get { return Image.FromStream(new MemoryStream(LargeBits)) as Bitmap; }
            set { SetBits("Large", value); }
        }

       
    }
}
